{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "找到了: 4\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "ls = [7,9,12,15,65,78,100,200,250,1000]\n",
    "\n",
    "x = 1000\n",
    "\n",
    "index = -1\n",
    "for i in range(len(ls)):\n",
    "    if ls[i] == x:\n",
    "        index = i\n",
    "        break;\n",
    "\n",
    "if index== -1:\n",
    "    print(\"没找到\")\n",
    "else:\n",
    "    print(\"找到了:\",index)\n",
    "\n",
    "# 顺序查找  如果找1000 总共要比较10次\n",
    "# 二分法查找  总共要比较3次 效率高,条件式不许是有序\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "找到了 5\n"
     ]
    }
   ],
   "source": [
    "ls = [7,9,12,15,65,78,100,200,250,1000]\n",
    "target = eval(input(\"请输入查找元素\"))\n",
    "# 查找范围\n",
    "low,high= 0,len(ls)-1\n",
    "\n",
    "n = 0\n",
    "while True:\n",
    "    n += 1\n",
    "    print(\"第\",n,\"次判断\")\n",
    "    # 求中间那个位置\n",
    "    mid = (low+high)//2\n",
    "    # 判断这个位置是否是要找到数字\n",
    "    if target == ls[mid]:\n",
    "        print('找到了',mid)\n",
    "        break\n",
    "    elif target<ls[mid]:\n",
    "        # 查找左侧内容\n",
    "        high = mid-1\n",
    "    else:\n",
    "        # 查找右侧范围\n",
    "        low = mid+1\n",
    "    if low>=high:\n",
    "        print(\"不存在\")\n",
    "        break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
